#include <unistd.h>
#include <signal.h>
#include "app_runner.h"
#include "app_blt.h"

static int is_running = 1;

static void app_runner_exit(int)
{
    is_running = 0;
}

int app_runner_run(void)
{
    // 注册终止号回调函数
    signal(SIGINT, app_runner_exit);  // ctrl+c
    signal(SIGTERM, app_runner_exit); // kill

    int result = app_pool_init(5);
    if (result == -1)
    {
        log_debug("app_pool_init failed");
        return -1;
    }
    log_debug("线程池初始化完成");

    result = app_mqtt_init();
    if (result == -1)
    {
        log_debug("app_mqtt_init failed");
        return -1;
    }
    log_debug("mqtt初始化完成");
    Device_t *device = app_device_init(DEVICE_FILE, 0);
    if (app_blt_init(device) == -1)
    {
        log_error("蓝牙初始化失败");
        return -1;
    }
    log_debug("蓝牙初始化完成");

    app_device_start(device, 0);

    log_debug("设备初始化完成");
    while (is_running)
    {
        sleep(1);
    }

    // 释放资源
    app_device_destory(device);
    // 关闭线程池
    app_pool_close();
    // 关闭mqtt链接
    app_mqtt_close();
    return 0;
}
